package com.tjnu.losca.service.impl;

import com.tjnu.losca.service.TestService;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @author Losca
 * @date 2022/4/3 12:00
 */
@Service
public class TestServiceImpl implements TestService {
    @Override
    public boolean resumeDown(String resume, HttpServletResponse response) throws UnsupportedEncodingException {
        String fileName = resume;// 文件名
        if (fileName != null) {
            //设置文件路径
            File file = new File("C://image/"+ fileName);
            if (file.exists()) {
                // 清空缓冲区，状态码和响应头(headers)
                response.reset();
                // 设置ContentType，响应内容为json，编码为utf-8，此处设定的编码是文件内容的编码
                response.setContentType("application/json;charset=utf-8");
                // 以（Content-Disposition: attachment; filename="filename.jpg"）格式设定默认文件名，设定utf编码，此处的编码是文件名的编码，使能正确显示中文文件名
                response.setHeader("Content-Disposition", "attachment;fileName=" + fileName + ";filename*=utf-8''" + URLEncoder.encode(fileName, "utf-8"));
                // 实现文件下载
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    // 获取字节流
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }

                }
                catch (Exception e) {
                    System.out.println("Download failed!");
                    return false;
                }
                finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    return true;
                }
            }

        }
        return false;
    }

}
